package com.time.company.components.task;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.MultiImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.app.AppConfig;
import com.time.company.app.MyApplication;
import com.time.company.app.WXManager;
import com.time.company.base.BaseActivity;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.task.ClockOn;
import com.time.company.servermodel.Share;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ShareUtils;
import com.time.company.utils.SpanFormatter;
import com.time.company.utils.ToastUtils;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.TaskParameters;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhy.base.fileprovider.FileProvider7;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 打卡成功页
 * Created by Bing on 2017/11/28.
 * E-mail is tx16bing@163.com
 */

public class ClockScActivity extends BaseActivity implements View.OnClickListener, WbShareCallback {

    public static final int REQUEST_STORAGE_PERMISSION = 101;

    private static final String EXTRA_CLOCK_DATA = "extra_clock_data";
    private ClockOn mClockOn;

    private TextView tvTimeCoin, tvPeopleNum;
    private ImageView ivFriend, ivPublish, ivZone, ivWb;


    private BasicRequest request;
    private static int CLOCK_ON_USER_SHARE = 89;
    private String curChannel;

    // qq
    private Tencent mTencent;
    // Sina share
    public WbShareHandler shareHandler;

    private String localPicUrl;

    public static void start(Activity mContext, ClockOn clockOn) {
        Intent intent = new Intent(mContext, ClockScActivity.class);
        intent.putExtra(EXTRA_CLOCK_DATA, clockOn);
        mContext.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_sc, "打卡提交");
        mClockOn = (ClockOn) getIntent().getSerializableExtra(EXTRA_CLOCK_DATA);
        assignViews();
        if (null != mClockOn) {
            bindViews();
        }

        if (mTencent == null) {
            mTencent = Tencent.createInstance(getString(R.string.qq_app_id), this);
        }

        // Init sina share
        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();
    }

    private void assignViews() {
        tvTimeCoin = findView(R.id.tv_clock_sc_coin);
        tvPeopleNum = findView(R.id.tv_clock_sc_people);
        ivFriend = findView(R.id.iv_clock_sc_friend);
        ivPublish = findView(R.id.iv_clock_sc_publish);
        ivZone = findView(R.id.iv_clock_sc_zone);
        ivWb = findView(R.id.iv_clock_sc_wb);
        ivFriend.setOnClickListener(this);
        ivPublish.setOnClickListener(this);
        ivZone.setOnClickListener(this);
        ivWb.setOnClickListener(this);
    }

    private void bindViews() {
        Spannable cSpannable = SpanFormatter.getColoredSpannable(this, mClockOn.getTimeCoin(), R.color.colorSecondPrimary);
        tvTimeCoin.setText(SpanFormatter.format(getString(R.string.clock_sc_time_coin), cSpannable));
        tvPeopleNum.setText(String.format(getString(R.string.clock_sc_people_num), mClockOn.getTodayClockOnThisActUserNum()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_clock_sc_friend:
                curChannel = getString(R.string.share_channel_friend);
                andPermission();
                break;

            case R.id.iv_clock_sc_publish:
                curChannel = getString(R.string.share_channel_moment);
                andPermission();
                break;

            case R.id.iv_clock_sc_zone:
                curChannel = getString(R.string.share_channel_qq_zone);
                andPermission();
                break;

            case R.id.iv_clock_sc_wb:
                curChannel = getString(R.string.share_channel_wei_bo);
                andPermission();
                break;

            default:
                break;
        }
    }

    private void andPermission() {
        // 需要调用AndPermission来开启读写系统文件夹权限提示
        AndPermission.with(this)
                .requestCode(REQUEST_STORAGE_PERMISSION)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(ClockScActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == REQUEST_STORAGE_PERMISSION) {
                // 表示读写的权限申请通过
                AppConfig.getInstance().initDir();

                shareRequest();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == REQUEST_STORAGE_PERMISSION) {
                // 即使是用户选择了不在询问还是会toast该提示语
                ToastUtils.showShort(getString(R.string.external_permission_apply));
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(ClockScActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(ClockScActivity.this, 404).show();

            }
        }
    };

    public void shareRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            TaskParameters parameters = new TaskParameters();
            parameters.setCommand(getString(R.string.command_shareCompanyClockOn));
            parameters.setUserId(MyApplication.getInstance().getAccount());
            parameters.setActChildId(mClockOn.getActChildId());
            parameters.setThirdParty(curChannel);
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this,
                    CLOCK_ON_USER_SHARE, true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()) {
            if (what == CLOCK_ON_USER_SHARE) {
                final Share share = basicBean.parseData(Share.class);
                if (share == null) return;
                ShareUtils.getInstance().getSharePicPath(share.getPicUrl(), "share.jpg", new ShareUtils.ShareCallback() {
                    @Override
                    public void onSucceed(String path) {
                        localPicUrl = path;
                        if (TextUtils.isEmpty(localPicUrl)){
                            localPicUrl = ShareUtils.getInstance().getSharePicPath("share.jpg");
                        }
                        if (TextUtils.equals(curChannel, getString(R.string.share_channel_friend))){
                            //　分享给微信朋友
                            shareMoment(share, false);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_moment))) {
                            //　分享给微信朋友圈
                            shareMoment(share, true);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_qq_zone))) {
                            // 分享给QQ空间
                            shareOnQQ(share);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_wei_bo))) {
                            // 分享给微博
                            shareWeibo(share);
                        } else {
                            return;
                        }
                    }
                });
            }
        }
    }

    private void shareMoment(Share share, boolean isTimelineCb) {
        WXManager.instance().sendWebPageToWX(
                isTimelineCb,
                share.getAddress(),
                TextUtils.isEmpty(share.getTitle()) ? " " : share.getTitle(),
                share.getDescribe(),
                localPicUrl);
    }

    public void shareOnQQ(Share share) {
        final Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share.getAddress());
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPicUrl);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, share.getTitle());
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != mTencent) {
                    params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
                    mTencent.shareToQQ(ClockScActivity.this, params, qqShareListener);
                }

            }
        });
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            ToastUtils.showShort("Cancel");
        }

        @Override
        public void onComplete(Object response) {
            ToastUtils.showShort("Complete");
        }

        @Override
        public void onError(UiError e) {
            ToastUtils.showShort("Error : " + e.errorMessage);
        }
    };

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    private void shareWeibo(Share share) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.textObject = getTextObj(share);
        weiboMessage.imageObject = getImageObj();
        weiboMessage.mediaObject = getWebpageObj(share);
        weiboMessage.multiImageObject = getMultiImageObject(share);
        shareHandler.shareMessage(weiboMessage, false);

    }

    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj(Share share) {
        TextObject textObject = new TextObject();
        textObject.text = share.getTitle();
        return textObject;
    }

    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_share_wb);
        imageObject.setImageObject(bitmap);
        return imageObject;
    }

    private BaseMediaObject getWebpageObj(Share share) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = share.getTitle();
        mediaObject.description = getString(R.string.app_name);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_logo);
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = share.getAddress();
        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }

    private MultiImageObject getMultiImageObject(Share share) {
        MultiImageObject multiImageObject = new MultiImageObject();
        //pathList设置的是本地本件的路径,并且是当前应用可以访问的路径，现在不支持网络路径（多图分享依靠微博最新版本的支持，所以当分享到低版本的微博应用时，多图分享失效
        // 可以通过WbSdk.hasSupportMultiImage 方法判断是否支持多图分享,h5分享微博暂时不支持多图）多图分享接入程序必须有文件读写权限，否则会造成分享失败
        ArrayList<Uri> pathList = new ArrayList<>();
        pathList.add(FileProvider7.getUriForFile(this, new File(localPicUrl)));
        multiImageObject.setImageList(pathList);
        return multiImageObject;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null != shareHandler) {
            shareHandler.doResultIntent(intent, this);
        }
    }

    @Override
    public void onWbShareSuccess() {
        ToastUtils.showLong("分享成功");
    }

    @Override
    public void onWbShareCancel() {
        ToastUtils.showLong("分享取消");
    }

    @Override
    public void onWbShareFail() {
        ToastUtils.showLong("分享失败");
    }
}
